/**
 * 基础菜单 考试管理
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>考试管理-考试列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="user-search" label-suffix="：">
      <el-form-item label="考试名称">
        <el-input size="small" style="width:200px" v-model="formInline.examName" clearable placeholder="输入考试名称"></el-input>
      </el-form-item>
      <el-form-item label="分类">
        <el-select size="small" style="width:200px" v-model="inforTypeId" clearable placeholder="选择考试分类">
          <el-option
             v-for="item in typeList"
            :key="item.id"
            :label="item.examType"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="试卷">
        <el-select size="small" style="width:200px" v-model="inforPaperId" clearable placeholder="选择考试分类">
          <el-option
             v-for="item in paperList"
            :key="item.id"
            :label="item.paperName"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select size="small" style="width:200px" v-model="inforStatus" clearable placeholder="选择考试状态">
          <el-option
             v-for="item in stat"
            :key="item.id"
            :label="item.status"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="操作：">
        <el-button size="small" type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
        <el-button size="small" icon="el-icon-delete-solid" @click="clearList()">清空</el-button>
        <el-button size="small" type="info" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
        <el-button size="small" type="warning" icon="el-icon-link" @click="examType()">分类</el-button>
        <!-- <el-button size="small" type="danger" icon="el-icon-delete" @click="deleteAll(scope.$index, scope.row)">删除</el-button> -->
      </el-form-item>
    </el-form>

    <!--列表-->
    <el-table size="small" :data="examList" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column sortable prop="examName" label="考试名称" width="115">
      </el-table-column>
      <el-table-column sortable prop="examtype.examType" label="考试分类" width="115" >
      </el-table-column>
      <el-table-column sortable prop="paper.paperName" label="试卷名称" width="155">
      </el-table-column>
      <el-table-column sortable prop="beginTime" label="开始时间" width="155">
      </el-table-column>
      <el-table-column sortable prop="endTime" label="结束时间" width="155">
      </el-table-column>
      <el-table-column sortable prop="allTime" label="答题时长" width="101">
      </el-table-column>
      <el-table-column sortable prop="user.name" label="创建人" width="87">
      </el-table-column>
      <el-table-column sortable prop="createTime" label="创建时间" width="155">
      </el-table-column>
      <el-table-column sortable prop="status" label="状态" width="90">
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button size="small" type="success" icon="el-icon-view" @click="check(scope.$index, scope.row)">查看</el-button>
          <el-button size="small" type="info" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" type="primary" icon="el-icon-user"  @click="selUser(scope.$index, scope.row)">指派</el-button>
          <el-button size="small" type="danger" icon="el-icon-delete" v-if="scope.row.status != '正在进行'" @click="deleteExam(scope.$index, scope.row)">删除</el-button>
          <el-button size="small" type="danger" icon="el-icon-delete" v-if="scope.row.status == '正在进行'" disabled @click="deleteExam(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <Pagination :child-msg="pageparm" @call="callFather"></Pagination>

    <!-- 新增，编辑界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click="closeDialog" >
      <el-form label-width="100px" :model="examFrom" :rules="rules" ref="examFrom" label-suffix="：">
        <el-form-item label="考试名称" prop="examName">
          <el-input size="large" style="width:350px" v-model="examFrom.examName" clearable placeholder="请输入考试名称"></el-input>
        </el-form-item>
        <el-form-item label="分类名称" prop="typeId">
          <el-select size="large" style="width:350px" v-model="examFrom.typeId" clearable placeholder="选择考试分类">
          <el-option
             v-for="item in typeList"
            :key="item.id"
            :label="item.examType"
            :value="item.id">
          </el-option>
        </el-select>
        </el-form-item>
        <el-form-item label="试卷名称" prop="paperId">
          <el-select size="large" style="width:350px" v-model="examFrom.paperId" clearable placeholder="选择考试分类">
          <el-option
             v-for="item in paperList"
            :key="item.id"
            :label="item.paperName"
            :value="item.id">
          </el-option>
        </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="beginTime">
          <el-date-picker size="large" style="width:350px" v-model="examFrom.beginTime" clearable placeholder="请输入开始时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker size="large" style="width:350px" v-model="examFrom.endTime" clearable placeholder="请输入结束时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="答题时长" prop="allTime">
          <el-input size="large" style="width:350px" v-model="examFrom.allTime" clearable placeholder="请输入答题时长时间"></el-input>
        </el-form-item>
        <el-form-item label="考试状态" prop="status">
          <el-select size="large" style="width:350px" v-model="examFrom.status" clearable placeholder="选择考试状态">
          <el-option
             v-for="item in stat"
            :key="item.id"
            :label="item.status"
            :value="item.id">
          </el-option>
        </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="large" icon="el-icon-circle-close" @click="closeDialog">取消</el-button>
        <el-button size="large" type="success" :loading="loading" icon="el-icon-circle-check" class="title" @click="submitForm('examFrom')">保存</el-button>
      </div>
    </el-dialog>

     <!-- 指派界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisibles" width="30%" @click="closeDialog">
      <div class="block" label="选择：">
        <el-cascader style="width:350px" ref="cascader" size="large" :options="roleList" :props="props" clearable @change="zhipai"></el-cascader>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="large" icon="el-icon-circle-close" @click="closeDialog">取消</el-button>
        <el-button size="large" type="primary" :loading="loading" icon="el-icon-circle-check" class="title" @click="zpUser()">指派</el-button>
      </div>
    </el-dialog>
 
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
export default {
  data() {
    return {
      // 考试列表查询分页参数
      pageparm: {
        currentPage: 1, //当前页
        pageSize: 5, //决定每页显示多少条
        total: 10 //决定总条数
      },

      //考试列表拿取到的数据
      examList: [],
      
      //考试分类名称信息
      typeList: [],//考试分类信息(模糊查询分类条件)

      //考试试卷名称信息
      paperList: [],//考试试卷信息(模糊查询分类条件)
      
      //模糊查询返回的值
      formInline: {
        examName:'',
        startPage: 1,
        limit: 5,
      },
      inforTypeId:'', //分类名称的值
      inforPaperId:'',//试卷名称的值
      //状态
      stat:[{
        id: 1,
        status:'未开始'
      },{
        id: 2,
        status:'正在进行'
      },{
        id: 3,
        status:'已完成'
      }],
      inforStatus:'',

      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      editFormVisibles: false, //控制指派页面显示与隐藏
      title: '',
      //添加的数据  编辑的数据
      examFrom:{
        id:"",
        examName:"",
        typeId:"",
        paperId:"",
        beginTime:"",
        endTime:"",
        allTime:"",
        creator:"",
        status:""
      },
      upBegin:'',
      upEnd:'',
      upCreate:'',

      //指派的数据
      roleList: [],

      //指派获得当前考试id
      byExamId:'',

      props: {multiple:true, value:'id', label:'name',  children:'userList'},

      //选择的数据
      SU:[],

      //获得的用户id
      studentId:'',


      // rules表单验证
      rules: {
        deptName: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
        deptNo: [{ required: true, message: '请输入部门代码', trigger: 'blur' }]
      },

      user:{},

      //复选框选择的数据
      multipleSelection:[],

      id:[],

      stu:[],

    }
  },


  // 注册组件
  components: {
    Pagination
  },
  /**
   * 数据发生改变
   */

  /**
   * 创建完毕
   */
  //刷新
  created() {
    //调用获取考试列表方法
    this.getData();
    //调用获取考试分类的方法
    this.getExamType();
    //调用获取考试书卷的方法
    this.getPaper();
    //获取当前登录人信息
    this.user = JSON.parse(localStorage.getItem('userdata'))
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
//======================= 列  表  开  始 ===================================
    // 获取考试列表
    getData() {
      this.$axios.get('/api/infor/inforList',{
        params: {
          pageNum: this.pageparm.currentPage,
          pageSize: this.pageparm.pageSize,
        },
      })
      .then((res) => {
        console.log('获取的考试列表中数据是:', res);
        this.examList = res.data.list;
        console.log("考试列表数据",this.examList);
        this.pageparm.total = res.data.total;
        console.log("全列表总数据",this.pageparm.total);
        this.examList.forEach( (s)=>{
          if(s.status == 3){
            s.status = '已结束';
          }else if(s.status == 2){
            s.status = '正在进行';
          }else if(s.status == 1){
            s.status = '未开始';
          }
          console.log("全列表状态",s.status)
        })
      })
      .catch((e) => {
        console.log('获取考试列表数据失败');
      });
    },
//======================= 列  表  结  束 ===================================
    
//======================= 模糊查询  开  始 =================================
    //获取考试分类条件
    getExamType(){
      this.$axios.get('/api/infor/type')
      .then(res => {
        this.typeList = res.data;
        console.log('考试分类中数据是:', res);
      })
      .catch((e) => {
        console.log('考试分类获取数据失败');
      });
    },

    //获取考试试卷条件
    getPaper(){
      this.$axios.get('/api/infor/paper')
      .then(res => {
        this.paperList = res.data;
        console.log('考试试卷中数据是:', res);
      })
      .catch((e) => {
        console.log('考试试卷获取数据失败');
      });
    },

    // 搜索事件
    search() {
      this.pageparm.currentPage=1;
      this.$axios.get('/api/infor/search',{
        params: {
          examName: this.formInline.examName,
          status: this.inforStatus,
          typeId: this.inforTypeId,
          paperId: this.inforPaperId,
          pageNum: this.formInline.startPage,
          pageSize: this.formInline.limit
        }
      })
      .then(res => {
        this.examList = res.data.list;
        console.log('模糊查询获取的数据是:', this.examList);
        this.pageparm.total = res.data.total;
        console.log('模糊查询数据:', this.pageparm.total);
        this.examList.forEach( (s)=>{
          if(s.status == 3){
            s.status = '已结束';
          }else if(s.status == 2){
            s.status = '正在进行';
          }else if(s.status == 1){
            s.status = '未开始';
          }
          console.log("模糊查询状态",s.status)
        })
      })
      .catch((e) => {
        console.log('模糊查询获取数据失败');
      });
    },
//======================= 模糊查询  结  束 =================================

//===========================批量删除（未完成）============================
  //复选框选择
    handleSelectionChange(val){
      this.multipleSelection = val;
      console.log("复选框选择数据：",this.multipleSelection)
      for(let i=0 ; i<this.multipleSelection.length ; i++){
        console.log("选择的id：",this.multipleSelection[i].id)
        this.id += this.multipleSelection[i].id
      }
      console.log("id有哪些值",this.id)
    },

    //批量删除
    deleteAll(){
      this
      .$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        for(let i=0 ; i<this.multipleSelection.length ; i++){
          let ids = this.multipleSelection[i].id
        this.$axios
        .get("/api/exam/delAll" , {
        params: {
          id: ids
        }
      })
        .then(res => {
          console.log("数据",res)
          if (res.data=='success') {
            this.$message({
              type: 'success',
              message: '考试分类已删除!'
              })
              this.getData()
          } else {
            this.$message({
              type: 'info',
              message: res.msg
            })
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('考试分类删除失败，请稍后再试！')
        })
        }
      })
      .catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
//=======================================================================
//======================= 添加，编辑  开  始 ===============================
    //显示新增，编辑界面
    handleEdit: function(index, row) {
      console.log("编辑：",row)
      
      this.editFormVisible = true
      this.editFormVisibles = false
      if (row != undefined && row != 'undefined') {
        this.upBegin=row.beginTime;
        this.upEnd=row.endTime;
        this.upCreate=row.createTime;
        this.title = '修改';
        this.examFrom.id = row.id;
        this.examFrom.examName = row.examName;
        this.examFrom.typeId = row.examtype.id;
        this.examFrom.paperId = row.paper.id;
        this.examFrom.beginTime = row.beginTime;
        this.examFrom.endTime = row.endTime;
        this.examFrom.allTime = row.allTime;
        if( row.status == '已结束'){
          this.examFrom.status = 3;
        }else if(row.status =='正在进行'){
          this.examFrom.status = 2;
        }else if(row.status =='未开始'){
          this.examFrom.status = 1;
        }  
      } else {
        this.title = '添加';
        this.examFrom.id = '';
        this.examFrom.examName = '';
        this.examFrom.typeId = '';
        this.examFrom.paperId = '';
        this.examFrom.beginTime = '';
        this.examFrom.endTime = '';
        this.examFrom.allTime = '';
        this.examFrom.status = '';
      }
    },

    //日期格式化
    formatTime(date) { 
      let year = date.getFullYear()
      let month= date.getMonth()+ 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
      let day=date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      let hours=date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
      let minutes=date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
      let seconds=date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      // 拼接
      return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
    },

    // 编辑、增加页面保存方法
    submitForm(editData) {
      this.$refs[editData].validate(valid => {
        if (valid) {
          if(this.examFrom.id == ''){
            //添加=======================================
            if(this.examFrom.examName!='' && this.examFrom.typeId!='' && this.examFrom.paperId!='' && this.examFrom.beginTime!='' && this.examFrom.endTime!='' && this.examFrom.allTime!='' && this.examFrom.status!=''){
              let begintime = this.formatTime(this.examFrom.beginTime)
              this.examFrom.beginTime = begintime.substr(0,10)
              let endtime = this.formatTime(this.examFrom.endTime)
              this.examFrom.endTime = endtime.substr(0,10)
              this.examFrom.creator = this.user.id;
              this.$axios.post("/api/infor/add",this.examFrom)
              .then(res=>{
                this.editFormVisible = false
                this.loading = false
                this.getData()
                this.$message({
                  type: 'success',
                  message: '考试添加成功！'
                })
              })
              .catch(err => {
                this.editFormVisible = false
                this.loading = false
                this.$message.error('添加失败，请稍后再试！')
              })
            }else{
              this.$message.error('信息不完整，请填写完整');
            }
          }else{
            //编辑=====================================
            if(this.examFrom.examName!='' && this.examFrom.typeId!='' && this.examFrom.paperId!='' && this.examFrom.beginTime!=null && this.examFrom.endTime!=null && this.examFrom.allTime!='' && this.examFrom.status!=''){
              if(this.examFrom.beginTime != this.upBegin ){
                let begintime = this.formatTime(this.examFrom.beginTime)
                this.examFrom.beginTime = begintime.substr(0,10)
              }
              if(this.examFrom.endTime != this.upEnd ){
                let endtime = this.formatTime(this.examFrom.endTime)
                this.examFrom.endTime = endtime.substr(0,10)
              }
              this.$axios.post("/api/infor/update",this.examFrom)
              .then(res=>{
                this.editFormVisible = false
                this.loading = false
                this.getData()
                this.$message({
                  type: 'success',
                  message: '考试修改成功！'
                })
              })
              .catch(err => {
                this.editFormVisible = false
                this.loading = false
                this.$message.error('修改失败，请稍后再试！')
              })
            }else{
              this.$message.error('修改信息不能为空，请补充完整！');
            }  
          }
        } else {
          return false
        }
      })
    },
//======================= 添加，编辑  结  束 ===============================

//======================= 查  看  开  始 ===================================
    //查看学院考试页面
	  check(index,row){
      localStorage.userExam = JSON.stringify(row);
		  this.$router.push('/exam/test/showuserexam');
	  },
//======================= 查  看  结  束 ===================================

//======================= 指  派  开  始 ===================================
    //指派页面
    selUser: function(index, row) {
      this.byExamId = row.id;
      this.editFormVisibles = true
      this.editFormVisible = false
      this.title = "指派"
      this.getRole();
    },

    //获取所有信息
    getRole(){
      this.$axios.get('/api/role/selUser',{
        params:{
          examId: this.byExamId,
        }
      })
      .then(res => {
        console.log('指派数据是:', res);
        this.roleList = res.data;
        console.log('指派一级数据是:', this.roleList);
        console.log("roleList长度：",this.roleList.userList.length)
      })
      .catch((e) => {
        console.log('指派获取数据失败');
      });
    },

    zhipai(){
      let nodesObj = this.$refs['cascader'].getCheckedNodes();
      this.SU = nodesObj;
      console.log("SU数据：：",this.SU)
      console.log("SU长度：",this.SU.length)
      if(this.SU.length < this.roleList.userList.length){
        for(let i=0;i<this.SU.length ;i++){
          console.log("非全选数量：",this.SU.length);
          console.log("非全选id：",this.SU[i].data.id);
          this.studentId+= this.SU[i].data.id+',';
          console.log("非全选studentId:",this.studentId);
        }
        this.studentId=this.studentId.substring(0,this.studentId.length-1)
      }
      if(this.SU.length > this.roleList.userList.length){
        for(let i=1;i<this.SU.length ;i++){
          console.log("全选数量：",this.roleList.userList.length);
          console.log("全选id：",this.SU[i].data.id);
          this.studentId+= this.SU[i].data.id+',';
          console.log("全选studentId:",this.studentId);
        }
         this.studentId=this.studentId.substring(0,this.studentId.length-1)
      }
    },

    //指派保存方法
    zpUser(){
      alert(this.studentId)
      this.$axios.get('/api/infor/addStu',{
        params:{
          examId: this.byExamId,
          userId: this.studentId
        }
      })
      .then(res=>{
        this.editFormVisibles = false
        this.loading = false
        this.$message({
        type: 'success',
        message: '指派成功！'
        })
      })
      .catch(err => {
        this.$message.error('指派失败，请稍后再试！')
      }) 
      
    },
//======================= 指  派  结  束 ===================================

//======================= 删  除  开  始 ===================================
    // 删除一行数据
    deleteExam(index, row) {
      this
      .$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        this.$axios
        .get("/api/infor/delete" , {
        params: {
          id: row.id
        }
      })
        .then(res => {
          console.log("数据",res)
          if (res.data=='success') {
            this.$message({
              type: 'success',
              message: '考试已删除!'
              })


        //考试删除的同时，相应学员的考试也删除
          this.$axios.get("/api/infor/selAll",{
            params:{
              examId: row.id
            }
          })
          .then(res => {
            console.log("学员信息表数据",res)
          //判断该考试是否有学员做
            if(res.data.length != 0){
              this.$axios
                .get("/api/infor/delStu" , {
                params: {
                  examId: row.id
                }
              })
                .then(res => {
                  console.log("数据",res)
                  if (res.data=='success') {
                    this.$message({
                      type: 'success',
                      message: '相应学员考试已删除!'
                      })
                      this.getData()
                  } else {
                    this.$message({
                      type: 'info',
                      message: res.msg
                    })
                  }
                })
                .catch(err => {
                  this.loading = false
                  this.$message.error('考试删除失败，请稍后再试！')
                })
            }else{
              this.loading = false
              this.$message.error('没有对应学员考试信息！')
            }
          })
          .catch(err => {
            this.loading = false
            this.$message.error('没有对应学员考试信息！')
          })
                
        //==========================================
              this.getData()
          } else {
            this.$message({
              type: 'info',
              message: res.msg
            })
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('考试删除失败，请稍后再试！')
        })
      })
      .catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
//======================= 删  除  结  束 ===================================

//======================= 分  页  开  始 ===================================
    // 分页插件事件
    callFather(parm) {
      this.formInline.page = parm.currentPage;
      this.formInline.limit = parm.pageSize;
      this.pageparm.currentPage = parm.currentPage;
      this.pageparm.pageSize = parm.pageSize;
      this.getData();
    },
//======================= 分  页  结  束 ===================================

    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false;
      this.editFormVisibles = false
    },

    //添加跳转页面
    add(){
      this.$router.push('./addexam');
    },

    //分类页面
    examType(){
      this.$router.push('./examtype');
    },

    //清空
    clearList(){
      this.formInline.examName="";
      this.inforTypeId="";
      this.inforPaperId="";
      this.inforStatus=""
    },
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>
